<template>
  <div class="doc">
    <el-row type="flex" class="doc-header">
      <el-col :xl="7" :lg="8" :md="9">
        <el-row type="flex" align="middle">
          <el-select
            style="width: 50%"
            v-model="company"
            placeholder="请选择"
            @change="handleGetWellTree"
          >
            <el-option
              v-for="item in companySelect"
              :key="item.index"
              :label="item.company"
              :value="item.company"
            />
          </el-select>
          <el-input
            style="width: 50%; margin-left: 10px"
            placeholder="关键字查询井名"
            v-model="filterText"
          />
        </el-row>
      </el-col>
      <el-col :xl="17" :lg="16" :md="15">
        <el-row type="flex" align="middle" justify="end">
          <el-input
            style="width: 150px; margin-right: 10px"
            v-model="newFolderName"
            placeholder="新文件夹名"
            :disabled="filePathUp ? false : true"
          ></el-input>
          <el-button
            type="primary"
            @click="newFolder"
            :disabled="filePathUp ? false : true"
            >新建文件夹</el-button
          >
          <el-upload
            style="display: inline-block; margin: 0 10px"
            class="upload-demo"
            ref="upload"
            action="#"
            :http-request="uploadFile"
            :on-remove="handleRemove"
            :show-file-list="false"
            :auto-upload="true"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :disabled="filePathUp ? false : true"
          >
            <el-button :disabled="filePathUp ? false : true" type="primary"
              >上传文件</el-button
            >
          </el-upload>

          <!-- <el-button type="primary" @click="handleDownloadFile(filePath)"
            >下载</el-button
          >
          <el-button type="primary" @click="handlePreviewFile(filePath)"
            >预览</el-button
          > -->
        </el-row>
      </el-col>
    </el-row>

    <el-row
      type="flex"
      :style="{ height: docMainHeight, 'background-color': '#eef0f6' }"
    >
      <el-col style="width: 300px; padding: 0 5px 5px 5px">
        <el-tree
          node-key="label"
          class="filter-tree"
          :data="wellTreeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          ref="tree1"
          :check-on-click-node="true"
          highlight-current
          accordion
          :default-expanded-keys="handldGetDefaultExpandedKeys(wellTreeData)"
          @node-click="handleClickWell"
          check-strictly
          :style="{ overflow: 'auto', height: treeHeight }"
        />
      </el-col>
      <el-col style="padding: 0 5px 5px 0">
        <el-tree
          default-expand-all
          node-key="filePath"
          class="filter-tree"
          :data="fileTreeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          ref="tree"
          :check-on-click-node="true"
          :highlight-current="true"
          accordion
          @node-click="handleClickFile"
          check-strictly
          :style="{ overflow: 'auto', height: treeHeight }"
        >
          <span
            class="treeSpan"
            slot-scope="{ node, data }"
            @mouseenter="treeCellMouseEnter"
            @mouseleave="treeCellMouseLeave"
          >
            <label>
              <label style="margin-right: 5px">
                <img
                  v-if="data.children"
                  src="../../assets/file_icon/folder.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="getFileIcon(node.label) === 'pdf'"
                  src="../../assets/file_icon/pdf.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="getFileIcon(node.label) === 'docx'"
                  src="../../assets/file_icon/docx.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="
                    getFileIcon(node.label) === 'xlsx' ||
                    getFileIcon(node.label) === 'xls'
                  "
                  src="../../assets/file_icon/xlsx.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="
                    getFileIcon(node.label) === 'ppt' ||
                    getFileIcon(node.label) === 'pptx'
                  "
                  src="../../assets/file_icon/ppt.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="getFileIcon(node.label) === 'txt'"
                  src="../../assets/file_icon/txt.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else-if="getFileIcon(node.label) === 'zip'"
                  src="../../assets/file_icon/zip.png"
                  alt=""
                  :height="16"
                />
                <img
                  v-else
                  src="../../assets/file_icon/other.png"
                  alt=""
                  :height="16"
                />
              </label>
              <label>{{ node.label }}</label>
            </label>
            <label class="hoverClass">
              <!-- <label
                v-if="data.children"
                style="margin: 0px 10px; cursor: pointer"
                @click.stop="handleDownloadFile(data.filePath)"
              >
                <i class="el-icon-upload"></i> 上传
              </label> -->
              <label
                v-if="!data.children"
                style="margin: 0px 10px; cursor: pointer"
                @click.stop="handleDownloadFile(data.filePath)"
              >
                <i class="el-icon-download"></i> 下载
              </label>
              <label
                v-if="!data.children"
                style="margin: 0px 10px; cursor: pointer"
                @click.stop="handlePreviewFile(data.filePath)"
              >
                <i class="el-icon-view"></i> 预览
              </label>
              <label
                style="margin: 0px 5px; cursor: pointer"
                @click.stop="handleDeleteFile(data)"
              >
                <i class="el-icon-delete"></i> 删除
              </label>
            </label>
          </span>
        </el-tree>
      </el-col>
      <el-drawer
        title="手动输入文件上传地址，如：LD10-3-1\固井作业"
        :visible.sync="drawer"
        size="30%"
        :before-close="handleClose"
      >
        <span>
          <el-input
            v-model="input"
            placeholder="请输入地址"
            clearable
          ></el-input>
        </span>
      </el-drawer>
      <el-card id="progress-card" class="box-card progress-percent">
        <el-row type="flex" justify="end">
          <i
            class="el-icon-close progress-card-i"
            style="cursor: pointer"
            @click="closeProgressCard"
          />
        </el-row>
        <el-row v-for="item in progressPercents" :key="item.name">
          <label style="font-size: 16px">{{ item.name }}</label>
          <el-progress
            :text-inside="true"
            :stroke-width="20"
            :color="customColors"
            :percentage="item.progressPercent"
          />
        </el-row>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { Tag } from 'element-ui'
import pdf from 'vue-pdf'
import Vue from 'vue'
import { COOKIE_LIST, SERVER_URL } from '@/util/constant'
import Cookie from 'js-cookie'
import {
  downloadPDF,
  getTree,
  getPath,
  upFile,
  getNew,
  deleteFile,
} from '@/api/module/well'
import { Upload, Drawer, Progress } from 'element-ui'
import {
  getWell,
  getWellDocTree,
  getWellById2,
  getCompany,
  getWellById3,
} from '@/api/module/wellFind'
import axios from 'axios'

export default {
  components: {
    pdf,
    elUpload: Upload,
    elDrawer: Drawer,
    elTag: Tag,
    elProgress: Progress,
  },
  watch: {
    filterText(val) {
      this.$refs.tree1.filter(val)
    },
  },
  data() {
    return {
      company: '',
      companySelect: [],
      wellTreeData: [],
      selectWellName: '',
      filterText: '',
      fileTreeData: [],
      newFolderName: '',
      newFolderPath: '',
      uploadFliePath: '',
      drawer: false,
      fileList: [],
      filePathUp: '',
      input: '',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 文件上传设定token
      header: {
        Authorization: Cookie.get(COOKIE_LIST.AUTHORIZATION),
      },
      docMainHeight: null,
      treeHeight: null,
      progressPercents: [],
      customColors: [
        { color: '#409eff', percentage: 99 },
        { color: '#5cb87a', percentage: 100 },
      ],
    }
  },
  created() {
    this.getMainHeight()
    window.onresize = () => {
      this.getMainHeight()
    }
  },
  mounted() {
    this.handleGetCompany()
  },
  methods: {
    // 获得公司下拉框
    handleGetCompany() {
      getCompany()
        .then((res) => {
          // res.data.data2 - array
          this.companySelect = res.data.data2
          // res.data.data3 - string
          this.company = res.data.data3
          this.handleGetWellTree()
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },

    // 查询 井 数据
    handleGetWellTree() {
      const companyName = encodeURIComponent(this.company)
      getWellById3(companyName)
        .then((res) => {
          this.wellTreeData = res.data.data
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 默认展开 井 数据，第一级和第二级
    handldGetDefaultExpandedKeys(data){
      let res = []
      data.forEach(d1 => {
        res.push(d1.label)
        d1.children.forEach(d2 => res.push(d2.label))
      })
      console.log(res)
      return res
    },

    // 查询 文件树
    getWellTree() {
      this.uploadFliePath = this.selectWellName
      getTree(this.selectWellName)
        .then((res) => {
          this.fileTreeData = res.data.data
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },

    // 新建文件夹
    newFolder() {
      this.newFolderPath = encodeURIComponent(
        `${this.filePathUp}\\${this.newFolderName}`.replace(/\\/g, 'xiegang')
      )
      getNew(this.newFolderPath)
        .then((res) => {
          this.getWellTree()
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },

    // 下载 文件，传入文件名
    handleDownloadFile(fileName) {
      const downloadFileUrl = fileName
        .replace(/\\/g, 'xiegang')
        .replace(/:/, '%3A')
      downloadPDF(downloadFileUrl)
        .then((res) => {
          this.fileDownload(res.data, fileName)
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },

    // 封装的下载方法
    fileDownload: function (data, fileName) {
      let blob = new Blob([data], {
        // type类型后端返回来的数据中会有，根据自己实际进行修改
        type: 'application/octet-stream',
      })
      let filename = fileName.split('\\').pop()
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        var blobURL = window.URL.createObjectURL(blob)
        var tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    },

    // 动态获取网页高度
    getMainHeight() {
      let height = window.innerHeight
      this.docMainHeight = height - 150 + 'px'
      this.treeHeight = height - 160 + 'px'
    },

    // 处理文件、文件夹前面图标现实
    getFileIcon(fileName) {
      let suffixs = fileName.split('.')
      return suffixs.pop()
    },

    // 鼠标移入树节点，显示操作按钮
    treeCellMouseEnter(e) {
      // 显示操作条  找一个特殊的条件判断，否则影响其他元素
      e.target.children[1].style.display = 'inline'
    },

    // 鼠标移出树节点，隐藏操作按钮
    treeCellMouseLeave(e) {
      e.target.children[1].style.display = 'none'
    },

    // 上传文件
    uploadFile(data) {
      this.getProgressCard()
      let formData = new FormData()
      formData.append('file', data.file)
      formData.append('wellName', this.uploadFliePath)

      const uploadUrl = SERVER_URL + '/dataQuery/upload/'
      const config = {
        headers: this.header,
        onUploadProgress: (progressEvent) => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          let progressPercent = parseFloat(
            ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)
          )
          let flag = true
          this.progressPercents.forEach((p) => {
            if (p.name === data.file.name) {
              p.progressPercent = progressPercent
              flag = false
            }
          })
          if (flag) {
            this.progressPercents.push({
              progressPercent,
              name: data.file.name,
            })
          }
        },
      }
      axios.post(uploadUrl, formData, config).then((res) => {
        if (res.status === 200) {
          this.newWell()
        }
      })
    },

    // 打开上传文件进度条
    getProgressCard() {
      let card = document.getElementById('progress-card')
      card.style.display = 'block'
    },

    // 关闭上传文件进度条
    closeProgressCard() {
      let card = document.getElementById('progress-card')
      card.style.display = 'none'
    },

    // 删除文件、文件夹
    handleDeleteFile(data) {
      let filePath = ''
      if (data.filePath) {
        let filePaths = data.filePath.split('\\')
        filePaths.shift()
        filePaths.shift()
        filePath = filePaths.join('//')
      } else {
        filePath = data.fileParent.replace(/\\/g, '//')
      }

      this.$confirm(`是否删除文件或文件夹：${data.label}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteFile({ filePath })
          .then((res) => {
            this.getWellTree()
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },

    handleSuccess(response, file, fileList) {
      this.$message.success(` 上传成功`)
      this.newWell()
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },

    //手动刷新
    newWell() {
      this.getWellTree()
      alert('大文件上传如未刷新成功，请稍后再试')
    },

    submitUpload() {
      this.$refs.upload.submit()
    },

    handleRemove(file, fileList) {
      console.log(file, fileList)
    },

    handlePreview(file) {
      this.form.fileName = file.name[0]
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },

    beforeUpload(file, fileList) {
      this.uploadFliePath = encodeURIComponent(
        this.filePathUp.replace(/\\/g, 'xiegang')
      )
      return this.$confirm(
        `确定上传到 ${this.filePathUp}？(如地址错误请双击后重试)`
      )
    },

    // 预览
    handlePreviewFile(fileName) {
      let wellName = fileName.replace(/\\/g, 'xiegang').replace(/:/, '%3A')
      let suffix_wellName = wellName.split('.').pop()
      let suffixs = [
        'png',
        'PNG',
        'jpg',
        'JPEG',
        'bmp',
        'tif',
        'gif',
        'pdf',
        // 'docx',
        // 'xlsx',
        // 'xls',
        // 'pptx',
        // 'ppt',
        // 'txt',
      ]
      if (suffixs.includes(suffix_wellName)) {
        window.open(SERVER_URL + '/dataQuery/preview/' + wellName)
      } else {
        alert('该文件格式不支持预览')
      }
    },

    // 获得文件名以及路径
    handleClickFile(data) {
      this.$refs.tree.setCheckedNodes([data])
      if (data.children) {
        let filePath01 = data.fileParent.split('\\')
        var filePath02 = ''
        for (let index = 0; index < filePath01.length; index++) {
          filePath02 = filePath02 + filePath01[index] + '\\'
        }
        filePath02 = filePath02.substring(0, filePath02.length - 1)
        this.filePathUp = filePath02
      }
    },

    // 点击叶子节点触发方法
    handleClickWell(data) {
      this.$refs.tree.setCheckedNodes([data])
      if (!data.children.length) {
        console.log(data.label)
        this.selectWellName = data.label
        this.filePathUp = data.label
        this.getWellTree()
      }
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
  },
}
</script>
<style scoped>
.el-tree >>> .el-tree-node__content:hover {
  background: #f0f7ff;
  color: black;
  font-weight: bold;
}
.tree-high-light {
  background-color: black;
}
.doc {
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
}
.doc-header {
  height: 60px;
  background-color: #eef0f6;
  padding: 10px;
}
.treeSpan {
  font-size: 14px;
  display: inline-block;
  width: 100%;
}
.hoverClass {
  position: absolute;
  right: 40px;
  display: none;
  color: #1187f5;
}
.progress-percent {
  position: fixed;
  bottom: 30px;
  right: 25px;
  display: none;
  width: 40vw;
  min-height: 20vh;
}
.progress-card-i {
  cursor: pointer;
}
.progress-card-i:hover {
  background-color: red;
  color: #fff;
  border-radius: 50%;
}
</style>
